package com.solocredit.finance.ui.market.impl

import android.content.Context
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.market.view.IMullaApplyView
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/05 13:45
 * @Annotation：贷款申请 Presenter 实现
 */
class MullaApplyPresenterImpl(context: Context?) : MvpPresenter<IMullaApplyView>(context) {

    private var applyModel: MullaApplyModelImpl? = null
    init {
        applyModel = MullaApplyModelImpl()
    }

    /**
     * 获取贷款信息
     */
    fun loadMullaApplyDataAction(){
        val params = JSONObject().addCommonParams().addRandomParams()
//        params.put("path", ApiService.API_PATH.MULLA_API_LOAN_APPLY_CUSTOM_LIMIT_PATH)
        params.put("product",mvpView?.loadProductName())
        params.put("token",mvpView?.loadProductToken())
        params.put("amount",mvpView?.getMullaApplyAmount())
        if (MullaConfigs.isSwahili()){
            params.put("localLanguage","YES")
        }
        val applyDays = mvpView?.getMullaApplyDays()
        applyDays?.let {
            if (it.isNotEmpty()){
                params.put("days",it)
            }
        }
        applyModel?.loadMullaApplyDataAction(params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            //是否允许修改申请金额，不允许修改则不显示Seekbar
                            val chooseAmountFlag = obj.optBoolean("chooseAmountFlag",false)
                            when(chooseAmountFlag){
                                true -> {//允许选择贷款额度
                                    mvpView?.showMullaOptionalViews(obj)
                                }
                                else -> {//不允许选择贷款额度
                                    mvpView?.showMullaNotOptionalViews()
                                }
                            }
                            //设置贷款期限
                            mvpView?.showMullaDurationList(obj)
                            //设置明细
                            mvpView?.showMullaDetailsList(obj)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showMullaNetworkErrorDialog("Apply Page Get LoanDetails", onRetryClick = {
                        mvpView?.showMullaLoading()
                        loadMullaApplyDataAction()
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 获取优惠券列表
     */
    fun loadMullaCouponListAction(){
        val dataString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_USER_COUPON_INFO)
        var useCount = 0
        if (dataString.isNotEmpty()){
            val couponArray = JSONArray(dataString)
            for (i in 0..<couponArray.length()){
                val item = JSONObject(couponArray.optJSONObject(i).optString("couponInfo"))
                val applyAmount = mvpView?.getMullaApplyAmount()
                applyAmount?.let {
                    if (item.optLong("fullAmount",0) <= it.toFloat()){
                        useCount += 1
                    }
                }
            }
        }
        mvpView?.showMullaCouponCounts(useCount)
    }

    /**
     * 创建贷款申请订单
     */
    fun onMullaCreateApplyOrderAction(){
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_LOAN_APPLY_ORDER_CREATE_PATH)
            put("product",mvpView?.loadProductName())
            put("token",mvpView?.loadProductToken())
            put("amount",mvpView?.getMullaApplyAmount())
            put("days",mvpView?.getMullaApplyDays())
        }
        applyModel?.onMullaCreateApplyOrderAction(params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.hideMullaLoading()
                val msg = data.optString("msg")
                when(data.optInt("code")) {
                    0 -> {//成功
                        mvpView?.showMullaApplySuccess()
                    }
                    else -> {
                        mvpView?.showMullaToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showMullaNetworkErrorDialog("Apply Page Loan Apply", onRetryClick = {
                        mvpView?.showMullaLoading()
                        onMullaCreateApplyOrderAction()
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

}